﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace JinKaiBodyCheck.Common.Helper
{
    public static class WeHelper
    {
        //微信开发者appId
        public static string appId
        {
            set;
            get;
        }

        //微信开发者secret
        public static string secret
        {
            set;
            get;
        }

        private static readonly string tokenUrl = "https://api.weixin.qq.com/cgi-bin/token";

        private static readonly string ticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken()
        {

            if (RedisTool.Get("BodyCheck_Wx_AccessToken") == null)
            {
                StringBuilder sbUrl = new StringBuilder();
                sbUrl.AppendFormat(tokenUrl);
                sbUrl.AppendFormat("?grant_type=client_credential");
                sbUrl.AppendFormat("&appid={0}", appId);
                sbUrl.AppendFormat("&secret={0}", secret);
                using (WebClient client = new WebClient())
                {
                    client.Encoding = Encoding.UTF8;
                    string data = client.UploadString(sbUrl.ToString(), string.Empty);
                    var result = JObject.Parse(data);
                    if (result["access_token"] != null && result["access_token"].Value<string>() != string.Empty)
                    {
                        string token = result["access_token"].Value<string>();
                        RedisTool.Add("BodyCheck_Wx_AccessToken", token, 120);
                        return token;
                    }
                    else
                        throw new Exception(data);
                }
            }
            else
            {
                return RedisTool.Get("BodyCheck_Wx_AccessToken").ToString();
            }
        }
        /// <summary>
        /// 获取Ticket
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static string GetTicket(string accessToken)
        {

            if (RedisTool.Get("BodyCheck_Wx_Ticket") == null)
            {
                StringBuilder sbUrl = new StringBuilder();
                sbUrl.AppendFormat(ticket);
                sbUrl.AppendFormat("?access_token={0}", accessToken);
                sbUrl.AppendFormat("&type=jsapi");
                using (WebClient client = new WebClient())
                {
                    client.Encoding = Encoding.UTF8;
                    string data = client.UploadString(sbUrl.ToString(), string.Empty);
                    var result = JObject.Parse(data);
                    if (result["ticket"] != null && result["ticket"].Value<string>() != string.Empty)
                    {
                        string ticket = result["ticket"].Value<string>();
                        RedisTool.Add("BodyCheck_Wx_Ticket", ticket, 120);
                        return ticket;
                    }
                    else
                        throw new Exception(data);
                }
            }
            else
            {
                return RedisTool.Get("BodyCheck_Wx_Ticket").ToString();
            }
        }
        /// <summary>
        /// 获取签名
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="noncestr"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetSignature(string timestamp, string noncestr, string url)
        {
            string jsapi_ticket = GetTicket(GetAccessToken());

            string sign = SignatureCompute(noncestr, jsapi_ticket, timestamp, url);

            //使用sha1加密这个字符串
            return SignatureSha1(sign);
        }


        private static string SignatureCompute(string noncestr, string jsapi_ticket, string timestamp, string url)
        {

            //3.签名算法

            /*签名生成规则如下：
            参与签名的字段包括          noncestr（随机字符串）,
                                        jsapi_ticket(有效的票据), 
                                        timestamp（时间戳）, 
                                        url（当前网页的URL，不包含#及其后面部分） 
            。对所有待 签名参数 按照字段名的ASCII 码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串string1。
            这里需要注意的是所有参数名均为小写字符。对string1作sha1加密，字段名和字段值都采用原始值，不进行URL 转义。*/
            #region 3-1.签名参数 按照字段名的ASCII 码从小到大排序（字典序）后
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["timestamp"] = timestamp;
            dic["noncestr"] = noncestr;
            dic["url"] = url;
            dic["jsapi_ticket"] = jsapi_ticket;

            string[] arrkey = new string[] { "timestamp", "noncestr", "url", "jsapi_ticket" };
            arrkey = arrkey.OrderBy(n => n).ToArray();
            #endregion

            #region 3-2.使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串string1
            string signatureStr = "";
            foreach (string key in arrkey)
            {
                signatureStr += key + "=" + dic[key] + "&";
            }
            signatureStr = signatureStr.Substring(0, signatureStr.Length - 1);
            #endregion

            return signatureStr;
        }

        /// <summary>
        /// 4.签名字符串 SHA1加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string SignatureSha1(string str)
        {
            var sha1 = System.Security.Cryptography.SHA1.Create();

            byte[] bytes = Encoding.UTF8.GetBytes(str);
            byte[] bytesArr = sha1.ComputeHash(bytes);
            StringBuilder sb = new StringBuilder();
            foreach (var item in bytesArr)
            {
                sb.AppendFormat("{0:x2}", item);
            }

            return sb.ToString();
        }


        #region 工具类
        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <returns></returns>
        public static string CreateNonceStr()
        {
            int length = 16;
            string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string str = "";
            var rad = new Random();
            for (int i = 0; i < length; i++)
            {
                str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
            }
            return str;
        }

        /// <summary>
        /// 生成时间戳
        /// </summary>
        /// <returns></returns>
        public static string CreateTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
            return timestamp;
        }
        #endregion
    }

}
